@tool
@icon("icons/parallel_state.svg")
class_name ParallelState
extends State

var sub_states:Array[State] = []

func state_init(fsm:FSM):
	super.state_init(fsm)
	for child in get_children():
		if child is State:
			sub_states.append(child)
			child.state_init(fsm)
func on_enter(from_state:State):
	super.on_enter(from_state)
func on_update(delta:float):
	super.on_update(delta)
	if get_state_status() == GameEnum.StateStatus.Waiting:
		return
	for state in sub_states:
		state.on_update(delta)
func on_physics_update(delta:float):
	super.on_physics_update(delta)
	if get_state_status() == GameEnum.StateStatus.Waiting:
		return
	for state in sub_states:
		state.on_physics_update(delta)
func on_exit(to_state:State):
	for state in sub_states:
		state.on_exit(to_state) 
	super.on_exit(to_state)
func get_state_status() -> GameEnum.StateStatus:
	if cur_state_status == GameEnum.StateStatus.Closed and sub_states.all(func (s):return s.get_state_status() == GameEnum.StateStatus.Ready):
		cur_state_status = GameEnum.StateStatus.Ready
	return cur_state_status
func translate_state(st_state:State,to_state:State,st_state_path:Array[State],to_state_path:Array[State]):
	var st_state_temp:State = st_state_path.pop_back()
	var to_state_temp:State = to_state_path.pop_back()
	if not st_state_temp:
		if to_state_temp:
			on_enter(st_state)
			for state in sub_states:
				if state == to_state_temp:
					state.translate_state(st_state,to_state,st_state_path,to_state_path)
				else:
					state.translate_state(st_state,to_state,st_state_path,[])
		else:
			on_enter(st_state)
			for state in sub_states:
				state.translate_state(st_state,to_state,st_state_path,to_state_path)
	else:
		if to_state_temp:
			to_state_temp.translate_state(st_state,to_state,st_state_path,to_state_path)
	var st_state_temp_exist:bool = sub_states.has(st_state_temp)
	var to_state_temp_exist:bool = sub_states.has(to_state_temp)
	if st_state_temp_exist and to_state_temp_exist:
		if to_state_temp:
			to_state_temp.translate_type(st_state,to_state,st_state_path,to_state_path)
	elif not st_state_temp_exist and to_state_temp_exist:
		on_enter(st_state)
		for state in sub_states:
			state.translate_state(st_state,to_state,st_state_path,to_state_path)
		
func _get_configuration_warnings() -> PackedStringArray:
	var warnings = super._get_configuration_warnings()
	var child_count = 0
	for child in get_children():
		if child is State:
			child_count += 1
	if child_count < 2:
		warnings.append("ParallelState" + "至少需要两个State才有效，如果只需要一个State，建议不使用ParallelState")
	return warnings
